package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.ConsumptionRecordQueryDTO;
import com.example.service.ConsumptionRecordService;
import com.example.vo.ConsumptionRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 消费记录控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/consumption-record")
@CrossOrigin
public class ConsumptionRecordController {
    
    @Autowired
    private ConsumptionRecordService consumptionRecordService;
    
    /**
     * 根据ID查询消费记录
     */
    @GetMapping("/{id}")
    @RequirePermission("user:consumption:view")
    public Result<ConsumptionRecordVO> getConsumptionRecordById(@PathVariable Long id) {
        try {
            return consumptionRecordService.getConsumptionRecordById(id);
        } catch (Exception e) {
            log.error("查询消费记录失败", e);
            return Result.error("查询消费记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号查询消费记录
     */
    @GetMapping("/order/{orderNo}")
    @RequirePermission("user:consumption:view")
    public Result<ConsumptionRecordVO> getConsumptionRecordByOrderNo(@PathVariable String orderNo) {
        try {
            return consumptionRecordService.getConsumptionRecordByOrderNo(orderNo);
        } catch (Exception e) {
            log.error("根据订单号查询消费记录失败", e);
            return Result.error("查询消费记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户的消费记录列表
     */
    @GetMapping("/my")
    @RequirePermission("user:consumption:view")
    public Result<List<ConsumptionRecordVO>> getMyConsumptionRecords() {
        try {
            return consumptionRecordService.getMyConsumptionRecords();
        } catch (Exception e) {
            log.error("查询我的消费记录失败", e);
            return Result.error("查询我的消费记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询当前用户的消费记录
     */
    @GetMapping("/my/page")
    @RequirePermission("user:consumption:view")
    public Result<PageResult<ConsumptionRecordVO>> getMyConsumptionRecordPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String packageName,
            @RequestParam(required = false) String paymentMethod,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String orderNo) {
        try {
            ConsumptionRecordQueryDTO queryDTO = new ConsumptionRecordQueryDTO();
            queryDTO.setPackageName(packageName);
            queryDTO.setPaymentMethod(paymentMethod);
            queryDTO.setStatus(status);
            queryDTO.setOrderNo(orderNo);
            
            // 处理时间参数
            if (startTime != null && !startTime.trim().isEmpty()) {
                queryDTO.setStartTime(java.time.LocalDateTime.parse(startTime + "T00:00:00"));
            }
            if (endTime != null && !endTime.trim().isEmpty()) {
                queryDTO.setEndTime(java.time.LocalDateTime.parse(endTime + "T23:59:59"));
            }
            
            return consumptionRecordService.getMyConsumptionRecordPage(page, size, queryDTO);
        } catch (Exception e) {
            log.error("分页查询我的消费记录失败", e);
            return Result.error("分页查询我的消费记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前店长的收入记录列表
     */
    @GetMapping("/store-manager/income")
    @RequirePermission("store:income:view")
    public Result<List<ConsumptionRecordVO>> getStoreManagerIncomeRecords() {
        try {
            return consumptionRecordService.getStoreManagerIncomeRecords();
        } catch (Exception e) {
            log.error("查询店长收入记录失败", e);
            return Result.error("查询店长收入记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询当前店长的收入记录
     */
    @GetMapping("/store-manager/income/page")
    @RequirePermission("store:income:view")
    public Result<PageResult<ConsumptionRecordVO>> getStoreManagerIncomeRecordPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String packageName,
            @RequestParam(required = false) String paymentMethod,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String orderNo) {
        try {
            ConsumptionRecordQueryDTO queryDTO = new ConsumptionRecordQueryDTO();
            queryDTO.setUsername(username);
            queryDTO.setPackageName(packageName);
            queryDTO.setPaymentMethod(paymentMethod);
            queryDTO.setStatus(status);
            queryDTO.setOrderNo(orderNo);
            
            // 处理时间参数
            if (startTime != null && !startTime.trim().isEmpty()) {
                queryDTO.setStartTime(java.time.LocalDateTime.parse(startTime + "T00:00:00"));
            }
            if (endTime != null && !endTime.trim().isEmpty()) {
                queryDTO.setEndTime(java.time.LocalDateTime.parse(endTime + "T23:59:59"));
            }
            
            return consumptionRecordService.getStoreManagerIncomeRecordPage(page, size, queryDTO);
        } catch (Exception e) {
            log.error("分页查询店长收入记录失败", e);
            return Result.error("分页查询店长收入记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户消费统计信息
     */
    @GetMapping("/my/statistics")
    @RequirePermission("user:consumption:view")
    public Result<Map<String, Object>> getMyConsumptionStatistics() {
        try {
            return consumptionRecordService.getMyConsumptionStatistics();
        } catch (Exception e) {
            log.error("获取我的消费统计信息失败", e);
            return Result.error("获取我的消费统计信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前店长收入统计信息
     */
    @GetMapping("/store-manager/income/statistics")
    @RequirePermission("store:income:view")
    public Result<Map<String, Object>> getStoreManagerIncomeStatistics() {
        try {
            return consumptionRecordService.getStoreManagerIncomeStatistics();
        } catch (Exception e) {
            log.error("获取店长收入统计信息失败", e);
            return Result.error("获取店长收入统计信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取今日消费统计（管理员使用）
     */
    @GetMapping("/today/statistics")
    @RequirePermission("admin:consumption:statistics")
    public Result<Map<String, Object>> getTodayConsumptionStatistics() {
        try {
            return consumptionRecordService.getTodayConsumptionStatistics();
        } catch (Exception e) {
            log.error("获取今日消费统计失败", e);
            return Result.error("获取今日消费统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据时间范围获取消费统计（管理员使用）
     */
    @GetMapping("/statistics/date-range")
    @RequirePermission("admin:consumption:statistics")
    public Result<Map<String, Object>> getConsumptionStatisticsByDateRange(
            @RequestParam String startTime,
            @RequestParam String endTime) {
        try {
            return consumptionRecordService.getConsumptionStatisticsByDateRange(startTime, endTime);
        } catch (Exception e) {
            log.error("根据时间范围获取消费统计失败", e);
            return Result.error("获取消费统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询所有消费记录（管理员使用）
     */
    @GetMapping("/admin/page")
    @RequirePermission("admin:consumption:list")
    public Result<PageResult<ConsumptionRecordVO>> getConsumptionRecordPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Long storeManagerId,
            @RequestParam(required = false) String storeManagerName,
            @RequestParam(required = false) String packageName,
            @RequestParam(required = false) String paymentMethod,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String orderNo) {
        try {
            ConsumptionRecordQueryDTO queryDTO = new ConsumptionRecordQueryDTO();
            queryDTO.setPage(page);
            queryDTO.setSize(size);
            queryDTO.setUserId(userId);
            queryDTO.setUsername(username);
            queryDTO.setStoreManagerId(storeManagerId);
            queryDTO.setStoreManagerName(storeManagerName);
            queryDTO.setPackageName(packageName);
            queryDTO.setPaymentMethod(paymentMethod);
            queryDTO.setStatus(status);
            queryDTO.setOrderNo(orderNo);
            
            // 处理时间参数
            if (startTime != null && !startTime.trim().isEmpty()) {
                queryDTO.setStartTime(java.time.LocalDateTime.parse(startTime + "T00:00:00"));
            }
            if (endTime != null && !endTime.trim().isEmpty()) {
                queryDTO.setEndTime(java.time.LocalDateTime.parse(endTime + "T23:59:59"));
            }
            
            return consumptionRecordService.getConsumptionRecordPage(queryDTO);
        } catch (Exception e) {
            log.error("分页查询消费记录失败", e);
            return Result.error("分页查询消费记录失败：" + e.getMessage());
        }
    }
} 